<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!--添加角色按钮区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表区域-->
      <el-table :data="rolelist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', 'vcenter', i1 === 0 ? 'bdtop' : '']" v-for="(item1, i1) in scope.row.children" :key="scope.id">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级和三级权限-->
              <el-col :span="19">
                <!--通过for循环 嵌套渲染二级权限-->
                <el-row :class="['vcenter', i2 === 0 ? '' : 'bdtop']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" closable v-for="(item3, i3) in item2.children" @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini">删除</el-button>
            <el-button icon="el-icon-setting" type="warning" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配权限的对话框-->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%" @close="setRightDialogClosed" >
      <!--树形控件-->
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys">

      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!--添加角色的对话框-->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="30%" @close="addRoleDialogClosed" >
      <!--内容-->
      <el-form ref="addFormRef" :model="addData" :rules="addRules" label-width="100px">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="addData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:">
          <el-input v-model="addData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑角色的对话框-->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="30%" @close="editRoleDialogClosed" >
      <!--内容-->
      <el-form ref="editFormRef" :model="editData" :rules="editRules" label-width="100px">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="editData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:">
          <el-input v-model="editData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的数据
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      roleId: '',
      // 控制添加角色对话框的显示与隐藏
      addRoleDialogVisible: false,
      // 添加角色对话框的数据
      addData: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色对话框的数据验证规则
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur'}
        ]
      },
      // 控制编辑角色对话框的显示与隐藏
      editRoleDialogVisible: false,
      // 编辑角色的id
      editId: '',
      // 编辑角色对话框的数据
      editData: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色对话框的数据验证规则
      editRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur'}
        ]
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      let {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }

      this.rolelist = res.data
    },
    // 根据id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框询问是否删除
      let confirmResult = await this.$confirm('此操作将永久删除该权限节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      let {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

      if ( res.meta.status !== 200 ){
        return this.$message.error(res.meta.msg)
      }

      this.$message.success('删除成功')
      // this.getRolesList()
      role.children = res.data
    },
    async showSetRightDialog(row) {
      // 保存id
      this.roleId = row.id
      // 获取所有权限的数据
      let {data: res} = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }

      // 把获取至的权限数据保存到 data 中
      this.rightsList = res.data

      // 获取角色三级权限id
      this.getLeafKeys(row, this.defKeys)

      this.setRightDialogVisible = true
    },
    // 获取角色所有三级权限的id, 并保存到defKeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框的关闭操作
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 为角色分配权限
    async allotRights() {
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // ,号拼接
      let idStr = keys.join(',')

      let {data:res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')

      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 添加角色
    addRole() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起添加角色的请求
        let {data: res} = await this.$http.post('roles', this.addData)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加成功')
        // 添加成功, 刷新列表
        this.getRolesList()
        // 清除添加数据
        this.addData = {}
        // 关闭添加角色对话框
        this.addRoleDialogVisible = false
      })
    },
    // 监听关闭添加角色对话框事件
    addRoleDialogClosed() {
      // 清除验证信息
      this.$refs.addFormRef.resetFields()
    },
    // 监听编辑按钮点击操作
    showEditDialog(row) {
      // 填充数据
      this.editData = {
        roleName: row.roleName,
        roleDesc: row.roleDesc
      }
      // 保存角色id
      this.editId = row.id
      // 显示编辑角色对话框
      this.editRoleDialogVisible = true
    },
    // 编辑角色
    editRole() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起编辑角色的请求
        let {data: res} = await this.$http.put('roles/' + this.editId, this.editData)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.$message.success('编辑成功')

        // 编辑成功, 刷新列表数据
        this.getRolesList()
        // 清除编辑数据
        this.editData = {}
        this.editId = ''
        // 关闭编辑角色对话框
        this.editRoleDialogVisible = false
      })
    },
    // 监听关闭编辑角色对话框事件
    editRoleDialogClosed() {
      // 清除验证信息
      this.$refs.editFormRef.resetFields()
    },
  }
}
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop{
    border-top: 1px solid #eee;
  }

  .bdbottom{
    border-top: 1px solid #eee;
  }

  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
